package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.commons.util.Constants;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.vo.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {
    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private AnnouncementApi announcementApi;


    /**
     * 根据环信ID查询用户信息
     *
     * @param huanxinId
     * @return
     */
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        User user = userApi.findByhuanxinId(huanxinId);
        UserInfo userInfo = userInfoApi.findById(user.getId());
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);//copy同名同类型的属性
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }


        return userInfoVo;
    }

    //添加好友
    public void contacts(Long friendId) {
        //1、将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + friendId);
        if (aBoolean != true) {
            throw new BusinessException(ErrorResult.error());
        }
        //2、如果注册成功，记录好友关系到mongodb
        friendApi.save(UserHolder.getUserId(), friendId);
    }


    //分页查询联系人列表
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //1、调用API查询当前用户的好友数据 -- List<Friend>
        List<Friend> list = friendApi.findByUserId(UserHolder.getUserId(), page, pagesize);
        if (CollUtil.isEmpty(list)){
            return new PageResult(page,pagesize,0,list);
        }
        //2、提取数据列表中的好友id
        List<Long> friendId = CollUtil.getFieldValues(list, "friendId", Long.class);
        //3、调用UserInfoAPI查询好友的用户详情
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(friendId, userInfo);
        //4、构造VO对象
        List<ContactVo> list1 = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo1 = byIds.get(friend.getFriendId());
            if (userInfo1 != null) {
                ContactVo vo = ContactVo.init(userInfo1);
                list1.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0, list1);
    }

    /**
     * 分页查询点赞，评论，喜欢
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findlikes(Integer page, Integer pagesize,int type) {
        //根据当前用户ID查询comment表，获得互动数据.
        List<Comment> list = commentApi.findById(page, pagesize, UserHolder.getUserId(),type);
        // 2、提取数据列表中的评论人id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //3、调用UserInfoAPI查询好友的用户详情
        if (list==null||list.size()==0){
           return new PageResult(page,pagesize,0, list);
        }
        Map<Long, UserInfo> item = userInfoApi.findByIds(userIds, null);
        //4、构造VO对象
        List<CommentVo> list1 = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = item.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo init = CommentVo.init(userInfo, comment);
                list1.add(init);
            }
        }
        return new PageResult(page,pagesize,0,list1);
    }

    //分页查询公告列表
    public PageResult findAllAnnouncement(Integer page, Integer pagesize) {
     IPage<Announcement> announcementIPage = announcementApi.finAll(page,pagesize);
        List<Announcement> records = announcementIPage.getRecords();
        List<AnnouncementVo> list = new ArrayList<>();
        for (Announcement record : records) {
            AnnouncementVo init = AnnouncementVo.init(record);
            list.add(init);
        }
        return new PageResult(page,pagesize,0,list);
    }


    //删除好友
    public void remove(Long likeUserId) {
        Boolean aBoolean = huanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX +likeUserId);
        if (!aBoolean){
            throw new BusinessException(ErrorResult.error());
        }
        //删除好友
        friendApi.remove(likeUserId,UserHolder.getUserId());
    }
}
